# coding: utf-8
import web
from config.settings import database,get_autoincre_id
from datetime import datetime

collection=database["user"]

def register(i):
    i.uid=get_autoincre_id('user')
    return collection.insert(i)

def login(email, password):
    user = collection.find_one({'email':email, 'password':password})
    if not user:
      return False

    return user

#检查邮箱是否存在
#return True:存在，Flase:不存在
def is_email(email):
    user = collection.find_one({'email':email})
    if not user:
      return True

    return False

def auth(**pars):
    def decorator(func):
        def proxyFunc(iself, *args, **kw):
            c = web.cookies(email=None, usercode=None)
            auth = if_login(c)
            #结果处理
            if not auth:
                if web.ctx.method == 'GET':
                    raise web.seeother('/login')
                else:
                    web.header('Content-Type','text/html; charset=UTF-8')
                    return render_template('redirect_message.html',message=u"登陆失败",url="/home")
  
            else:
                return func(iself, *args, **kw)
        return proxyFunc
    return decorator

def if_login(cookie):
    auth = False
    try:
        email, usercode = cookie.email, cookie.usercode
        #验证
        if email and usercode:
            if sha1(email) == usercode:
                auth = True
    except Exception,e:
        pass
    return auth







